﻿#region Licence
// <copyright file="Core/NotificationService.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Core.Enums;
using Database.POCO;
using GalaSoft.MvvmLight.Ioc;
using Helpers.Extensions;
using Interfaces;
using Interfaces.Enums;

#endregion

namespace Core.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class NotificationService : IServiceNotification
    {
        /// <summary>
        /// 
        /// </summary>
        public IServiceDatabase DatabaseService
        {
            get { return SimpleIoc.Default.GetInstance<IServiceDatabase>(); }
        }

        /// <summary>
        /// 
        /// </summary>
        public IServiceAccessControlLayer AccessService
        {
            get { return SimpleIoc.Default.GetInstance<IServiceAccessControlLayer>(); }
        }

        /// <summary>
        /// Permet d'enregistrer une notification
        /// </summary>
        public void SaveNotification(string message, ValueNotificationEnum type, [CallerFilePath] string source = "", [CallerMemberName] string member = "")
        {
            var notif = new SysNotification
                        {
                            Sujet = message, 
                            Source = source, 
                            Appelant = member,
                            Type = (int)type
                        };
            DatabaseService.Service.Save<SysNotification>(notif, false);
        }

        /// <summary>
        /// Permet d'enregistrer une notification interactive pour un utilisateur
        /// </summary>
        public void SaveNotificationUser(string sujet, string message, ValueNotificationEnum type, Int64 idObject, SysUtilisateur utilisateur,
            TypeModulesEnum module, string source = "", string member = "")
        {
            if (utilisateur != null)
            {
                var notif = new SysNotificationUser()
                {
                    Sujet = sujet,
                    Resume = message,
                    IdObject = idObject,
                    Utilisateur = utilisateur,
                    Module = (int) module,
                    Source = source,
                    Appelant = member,
                    Type = (int) type
                };
                DatabaseService.Service.Add<SysNotificationUser>(notif);

                //On regarde si l'utilisateur fait parti d'un ou plusieurs groupes
                //Si oui on va envoyer une notification aux référents de ces groupes
                var referentsToSend = new List<SysUtilisateur>();
                foreach (var groupe in utilisateur.Groupes)
                {
                    SysGroupe groupe1 = groupe;
                    referentsToSend.AddRange(
                        DatabaseService.Service.Where<SysReferentGroupe>(r => r.Groupe.Code == groupe1.Code)
                            .ToList()
                            .Select(r => r.Referent));
                }

                foreach (var referent in referentsToSend.WithoutDuplicates())
                {
                    if (referent != utilisateur && referent != AccessService.CurrentUser)
                    {
                        var notifRef = new SysNotificationUser()
                        {
                            Sujet = sujet,
                            Resume = message,
                            IdObject = idObject,
                            Utilisateur = referent,
                            Module = (int) module,
                            Source = source,
                            Appelant = member,
                            Type = (int) type,
                            UtilisateurCible = utilisateur.FullName
                        };
                        DatabaseService.Service.Add<SysNotificationUser>(notifRef);
                    }
                }
                DatabaseService.Service.SaveChanges<SysUtilisateur>();
            }
        }

        /// <summary>
        /// Permet de renvoyer le nombre de notifications courantes
        /// </summary>
        /// <returns></returns>
        public int GetCountCurrentNotification()
        {
            try
            {
                var numberNotifications = 0;
                if (DatabaseService != null)
                {
                    //Droit de visualiser toutes les notifications systémes
                    if (AccessService.IsAuthorizedFunction(SimpleIoc.Default.GetInstance<IServiceRights>().GetIdentifiantRight((int)RightsEnum.ViewParametersSystem, TypeModulesEnum.Core)))
                    {
                        numberNotifications = DatabaseService.Service.Where<SysNotification>(n => n.IsRead == false).Count();
                    }

                    //Notifications utilisateur
                    numberNotifications += DatabaseService.Service.Where<SysNotificationUser>(n => n.Utilisateur.ID == AccessService.CurrentUser.ID && n.IsRead == false).Count();
                }
                return numberNotifications;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// Permet de renvoyer toutes les notifications systémes
        /// </summary>
        /// <returns></returns>
        public List<SysNotification> GetNotificationsSystem()
        {
            if (DatabaseService != null)
            {
                //Droit de visualiser toutes les notifications systémes
                if (AccessService.IsAuthorizedFunction(SimpleIoc.Default.GetInstance<IServiceRights>().GetIdentifiantRight((int)RightsEnum.ViewParametersSystem, TypeModulesEnum.Core)))
                {
                    return DatabaseService.Service.Where<SysNotification>(n => n.IsRead == false).ToList();
                }
            }
            return new List<SysNotification>();
        }

        /// <summary>
        /// Permet de renvoyer toutes les notifications de l'utilisateur courant
        /// </summary>
        /// <returns></returns>
        public List<SysNotificationUser> GetNotificationForCurrentUser()
        {
            if (DatabaseService != null)
            {
                return DatabaseService.Service.Where<SysNotificationUser>(n => n.IsRead == false).ToList();
            }
            return new List<SysNotificationUser>();
        }
    }
}
